package com.edu.admin.utils;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author Wangjiong
 *
 */
@Service
public class UploadUtil {

	public String upload(MultipartFile file, Long schoolId, HttpServletRequest request) throws Exception {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			String sfilename = file.getOriginalFilename();
			String suffix = sfilename.substring(sfilename.lastIndexOf(".") + 1);
			if (!suffix.equalsIgnoreCase("xls") && !suffix.equalsIgnoreCase("xlsx")) {
				return null;
			}
			String filePath = "";
			String fileName = "";
			try {
				// 文件保存路径
				filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\" + schoolId.toString() + "\\"+ DateUtils.getToday()+"\\";// "upload/"
				//System.out.println("filePath="+filePath);
				
				fileName = filePath + System.currentTimeMillis()  + "." + suffix;
				//System.out.println("fileName="+fileName);
				
				mkdirs(filePath);
								
				// 转存文件
				file.transferTo(new File(fileName));
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			return fileName;
		} else {
			return null;
		}
	}
	
	/**
     * 会自动创建不存在的目录
     */
 
   public void mkdirs(String path) {
        File f;
        try {
            f = new File(path);
            if (!f.exists()) {
                boolean i = f.mkdirs();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
   }

}
